package com.mdxq.mall.user.service.impl;

import com.mdxq.mall.user.entity.AdminLoginLog;
import com.mdxq.mall.user.mapper.AdminLoginLogMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.update.UpdateWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.mdxq.mall.user.entity.Admin;
import com.mdxq.mall.user.mapper.AdminMapper;
import com.mdxq.mall.user.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

/**
 * 后台用户表 服务层实现。
 *
 * @author ShuJie
 * @since 2025-01-12
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>  implements AdminService{
    //装配一个登录日志的mapper
    @Autowired
    private AdminLoginLogMapper adminLoginLogMapper;
    // 重写getById方法,注入角色和菜单数据
    @Override
    public Admin getById(Serializable id) {
        Admin admin=super.getById(id);//先调用父类的getById查询到管理员信息
        admin.setRoles(mapper.selectRolesByAdminId(admin.getId()));
        admin.setMenus(mapper.selectMenusByAdminId(admin.getId()));
        return admin;
    }

    @Override
    public Admin login(String username, String password, HttpServletRequest request){
        QueryWrapper queryWrapper=new QueryWrapper();
                        //      表的字段    客户端填写的账号
        queryWrapper.eq("username",username);
        queryWrapper.eq("status",1);//查询未被禁用的
        // 使用getOne方法需要保证查到的结果最多一条,否则会抛异常
        Admin admin=this.getOne(queryWrapper);
        if(admin!=null){//说明查到了这个账号,而且状态正常
            if(BCrypt.checkpw(password,admin.getPassword())){//校验通过返回true
                admin.setLoginTime(LocalDateTime.now());
                mapper.updateByQuery(admin,true,queryWrapper);
                AdminLoginLog adminLoginLog=new AdminLoginLog();
                adminLoginLog.setAdminId(admin.getId());
                adminLoginLog.setIp(request.getRemoteHost());
                adminLoginLog.setAddress(request.getRemoteAddr());
                adminLoginLog.setCreateTime(LocalDateTime.now());
                adminLoginLog.setUserAgent(request.getHeader("User-Agent"));
                adminLoginLogMapper.insert(adminLoginLog);
                return admin;
            }
        }
        return null;
    }
}
